package org.sczfdf.utils;

import org.sczfdf.conf.GlobalConf;
import org.sczfdf.constants.Constant;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Created by cgb
 * @date 2023/1/31
 */
public class PropertiesUtil {
    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            getConf0();
        } catch (IOException e) {
            LogUtil.logError("读取配置文件失败");
        }
    }

    public static String getConf(Constant c) {
        return PROPERTIES.getProperty(c.getKey(), c.getDefaultValue());
    }

    public static String getConf(String key, String defaultValue) {
        return PROPERTIES.getProperty(key, defaultValue);
    }

    public static void setConf(String key, String value) {
        PROPERTIES.setProperty(key, value);
    }

    public static String getConf(String key) {
        return PROPERTIES.getProperty(key);
    }

    public static boolean containsKey(String key) {
        return PROPERTIES.containsKey(key);
    }


    private static void getConf0() throws IOException {

        // 先找conf下的配置文件
        File confFile = new File(getPathConfDir(GlobalConf.get().getConfName()));
        if (confFile.exists()) {
            try (FileReader fileReader = new FileReader(confFile)) {
                PROPERTIES.load(fileReader);
            }
        }

        // 没有在找同级目录的
        confFile = new File(getPath(GlobalConf.get().getConfName()));
        if (confFile.exists()) {
            try (FileReader fileReader = new FileReader(confFile)) {
                PROPERTIES.load(fileReader);
            }
        }

    }

    private static String getPathConfDir(String fileName) {
        return GlobalConf.get().getRootDir() + File.separator +
                GlobalConf.get().getConfigDir() + File.separator +
                fileName;
    }

    private static String getPath(String fileName) {
        return GlobalConf.get().getRootDir() + File.separator + fileName;
    }
}
